package com.hugo.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hugo.eduservice.SubjectExcelListener.SubjectExeclListener;
import com.hugo.eduservice.entity.EduSubject;
import com.hugo.eduservice.entity.excel.SubjectData;
import com.hugo.eduservice.entity.subject.OneSubject;
import com.hugo.eduservice.entity.subject.TwoSubject;
import com.hugo.eduservice.mapper.EduSubjectMapper;
import com.hugo.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author hugo
 * @since 2020-09-07
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        try {
            //得到文件的输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, SubjectData.class,new SubjectExeclListener(eduSubjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public List<OneSubject> getTreeSubject() {
        //查询一级分类
        QueryWrapper<EduSubject> oneSubject = new QueryWrapper<>();
        oneSubject.eq("parent_id","0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(oneSubject);
        //查询二级分类
        QueryWrapper<EduSubject> twoSubject =new QueryWrapper<>();
        twoSubject.ne("parent_id","0");
        List<EduSubject> twoSubjectlist =baseMapper.selectList(twoSubject);

        //最后封装成层级list
        List<OneSubject> finalSubject =new ArrayList<>();

        for (int i = 0; i < oneSubjectList.size(); i++) {
            //得到每一个edusubject的值
            EduSubject eduSubject = oneSubjectList.get(i);
            //将里面的值遍历出来塞到onesubject里面去
            OneSubject oSubject=new OneSubject();
            //beanutils封装方法 将值塞进去
            BeanUtils.copyProperties(eduSubject,oSubject);
            finalSubject.add(oSubject);

            List<TwoSubject> twofinalSubject =new ArrayList<>();
            for (int a = 0; a < twoSubjectlist.size(); a++) {
                EduSubject tSubject = twoSubjectlist.get(a);
                if (tSubject.getParentId().equals(eduSubject.getId())){
                    TwoSubject twoSubject1=new TwoSubject();
                    BeanUtils.copyProperties(tSubject,twoSubject1);
                    twofinalSubject.add(twoSubject1);

                }


            }
            oSubject.setChildren(twofinalSubject);


        }

        return finalSubject;
    }
}
